package com.edu.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.edu.entity.GoodsToWeb;
import com.edu.entity.Orders;
import com.edu.entity.User;
import com.edu.entity.address;
import com.edu.service.impl.GoodServerImpl;
import com.edu.service.impl.OrdersServiceImpl;
import com.edu.service.impl.UserServerImpl;

/**
 * Servlet implementation class buyServlet
 */
@WebServlet(name = "buyDo", urlPatterns = { "/buyDo" })
public class buyServlet extends HttpServlet {
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		GoodServerImpl gsi = new GoodServerImpl();
		UserServerImpl usi = new UserServerImpl();
		HttpSession session = request.getSession();
		User logInUser = (User) session.getAttribute("logInUser");
		GoodsToWeb gtw = (GoodsToWeb) session.getAttribute("good");
		User seller = (User) gtw.getSeller();
		String getAddress = request.getParameter("buyerAddressid");
		System.out.println("地址为："+getAddress);
		int addId = Integer.parseInt(getAddress);
		System.out.println("地址id为："+addId);
		address buyerAddress = usi.findAddress(addId);
		Orders order = new Orders();
		order.setUserId(seller.getUserid());
		order.setTargetUserId(logInUser.getUserid());
		order.setAddressid(addId);
		UUID uuid = UUID.randomUUID();
	    int id = (int) Math.abs(uuid.getMostSignificantBits() % 10000000000L); // 10位数
	    String sId = "rvf_"+String.valueOf(id);
	    order.setCommodityId(gtw.getGoodid());
	    order.setOrderNo(sId);
	    String getDouble = request.getParameter("allPrice");
	    double price = Double.parseDouble(getDouble);
	    order.setMoney(price);
	    if(addId != 0) {
	    	order.setPayMethod(1);
	    }else {
	    	order.setPayMethod(2);
	    }
	    order.setState(4);
		OrdersServiceImpl osi = new OrdersServiceImpl();
		int ret = osi.addOrder(order);
		System.out.println(ret);
		PrintWriter pw = response.getWriter();
		pw.flush();
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
